package edu.jmu.action.sysmanage.role;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

import edu.jmu.action.BaseAction;
import edu.jmu.action.privilege.Permission;
import edu.jmu.bean.privilege.Privilege;
import edu.jmu.bean.privilege.Role;
import edu.jmu.service.sysmanage.PrivilegeService;
import edu.jmu.service.sysmanage.RoleService;

@Controller 
@Namespace("/sysmanage")
@Scope(value="prototype")
public class EditRoleAction extends BaseAction<Role>{
	private static final long serialVersionUID = 277466192267908798L;
	private Role role;
	private List<Privilege> privileges = new ArrayList<Privilege>();
	@Resource
	private RoleService roleService;
	@Resource
	private PrivilegeService privilegeService;
	@Validations(requiredStrings={
			@RequiredStringValidator(fieldName="role.name",message="角色名不能为空"),
			@RequiredStringValidator(fieldName="role.description",message="角色描述不能为空")
	},stringLengthFields={
			@StringLengthFieldValidator(fieldName="role.description",message="角色描述长度过长，因小于100个字符",maxLength="100")
	})
	@Action(value="editRole" ,results={
			@Result(name=SUCCESS,type="redirectAction",params={
					"actionName", "roleList"
			}),
			@Result(name=INPUT,location="/page/sysmanage/addRole.jsp")
	})
	@Permission(module="user",privilege="editRole")
	public String editRole(){
		role.setPrivileges(new HashSet<Privilege>(privileges));
		roleService.update(role);
		return SUCCESS;
	}
	@SkipValidation
	@Action(value="showRole" ,results={
			@Result(location="/page/sysmanage/editRole.jsp"),
			@Result(name=INPUT,location="/page/sysmanage/editRole.jsp")
	})
	@Permission(module="user",privilege="showRole")
	public String showRole(){
		if(role.getRoleId() == null || ("").equals(role.getRoleId())){
			return INPUT;
		}
		this.role = roleService.find(role.getRoleId());
		privileges = privilegeService.getScrollData().getResultlist();		
		return SUCCESS;
	}
	
	
	public Role getRole() {
		return role;
	}
	public void setRole(Role role) {
		this.role = role;
	}
	public List<Privilege> getPrivileges() {
		return privileges;
	}
	public void setPrivileges(List<Privilege> privileges) {
		this.privileges = privileges;
	}	
}
